var HTTP = require("http");
var URL = require("url");
var PATH = require("path");
var FS = require("fs");
var querystring = require("querystring");

//加载配置文件
var Config = require("./Config");

/**
 * 开始服务器
 * @param  {[type]} port 端口
 * @return {[type]}      
 */
function start(port){
	
	//加载网站物理根目录
	Config.ROOT = process.cwd();
	HTTP.createServer(onRequest).listen(port);

	console.log("Server started on " + port);
	console.log("debug model = " + Config.DEBUG 
				+ ", 静态文件夹 = " + Config.ASSERT);
}


/**
 * 新请求时的总方法
 * @param  {[type]} req [description]
 * @param  {[type]} res [description]
 * @return {[type]}     [description]
 */
function onRequest(req, res){
	var reqUrl = URL.parse(req.url);
	var fullPath = reqUrl.pathname;
	
	if(fullPath == "/favicon.ico"){
		res.end();
		return ;
	}

	console.log("request url:" + fullPath +", and  query = " + reqUrl.query);
	
	var realPath = Config.ROOT + fullPath;
	//判断是否请求的是静态文件夹中的内容
	if(fullPath.indexOf(Config.ASSERT) == 0){
		console.log("request assert! " + realPath);

		FS.exists(realPath, function(exist){
			//文件不存在时
			if(!exist){
				res.writeHead(404, {
					"content-type":"text/plain"
				});
				res.end(fullPath + " do not be found on this server!");
			}else{
				//文件存在，就读取文件，成功后，判断文件后缀，然后通过后缀返回相应的数据
				FS.readFile(realPath, "binary", function(err, file){
					if(err){
						res.writeHead(500, {
							"content-type":"text/plain"
						});
						res.write(err.toString());
						res.end();
					}else{
						var extName = PATH.extname(fullPath);
						extName = extName ? extName.slice(1) : "unknown";
						var mime = Config.MIME[extName] || "text/plain";
						console.log("mime = " + mime + " of " + extName);
						res.writeHead(200, {"content-type":mime});
						res.write(file, "binary");
						res.end();
					}
				});

			}
		});	
	}
	else{
		var httpData = "";
		req.on("data", function(data){
			console.log("get data:" + data);
			httpData += data;
		});

		req.on("end", function(){
			console.log("data get ok:" + httpData);
			req.P = querystring.parse(httpData);
			addGetParams(req, reqUrl.query);
			console.log(req.P);

			dispatcher(req, res, fullPath);
		});
	}
}


/**
 * 路由调配 action 与 method
 * @param  {[type]} req [description]
 * @param  {[type]} res [description]
 * @return {[type]}     [description]
 */
function dispatcher(req, res, fullPath){
	var mvc = bindActionAndMethod(fullPath);
		try{
			var A = require("../controller/" + mvc.action);
		}catch(e){
			res.end("no action name=" + mvc.action + " can be found on ./controller folder!");
			return ;
		}

		//调用方法
		if(A[mvc.method] && typeof(A[mvc.method]) === "function"){
			console.log("go " + mvc.method + " @ " +mvc.action);
			A[mvc.method](req, res);
		}else{
			res.end("no method name=" + mvc.method + " can be found controller " + mvc.action);
			return ;
		}
}

/**
 * 解析出 action 与 method， 如果没有，就使用config 中的默认值
 * @param  {[type]} path 
 * @return {[type]}      
 */
function bindActionAndMethod(path){
	
	var temp = path.split("/");
	
	var action = temp[1] || Config.ACTION,
		method = temp[2] || Config.METHOD;
	console.log("a=" + action + ", m=" + method);
	return {
		"action" : action,
		"method" : method
	};
}

/**
 * 将req的参数放置到req的P属性中
 * @param {[type]} req [description]
 */
function addGetParams(req, query){
	query = query || URL.parse(req.url).query;
	var PP = querystring.parse(query);

	for(var item in PP){
		req.P[item] = PP[item];
	}
}

exports.start = start;
